/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentacion;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import logica.ControladorCaracteristicas;
import logica.ControladorProductos;

/**
 *
 * @author Andres
 */
public class ListadoProductos extends javax.swing.JPanel {

    private ControladorCaracteristicas caracteristicas;
    private ControladorProductos productos;

    public ControladorCaracteristicas getCaracteristicas() {
        return caracteristicas;
    }

    public void setCaracteristicas(ControladorCaracteristicas caracteristicas) {
        this.caracteristicas = caracteristicas;
        if (this.caracteristicas != null && this.productos != null) {
            cargarTabla();
        }
    }

    public ControladorProductos getProductos() {
        return productos;
    }

    public void setProductos(ControladorProductos productos) {
        this.productos = productos;
        if (this.caracteristicas != null && this.productos != null) {
            cargarTabla();
        }
    }

    /**
     * Creates new form ListadoProductos
     */
    public ListadoProductos() {
        initComponents();
    }

    private void cargarTabla() {
        DefaultTableModel modelo = (DefaultTableModel) this.jTable1.getModel();
        while (modelo.getRowCount() != 0) {
            modelo.removeRow(0);
        }
        List<String> codigos = this.caracteristicas.getCaracteristica("descripciones");
        String marca, categoria, descripcion;
        for (String codigo : codigos) {
            Hashtable<String, String> datos = this.productos.cargarDatos(codigo);
            marca = datos.get("marca");
            categoria = datos.get("categoria");
            descripcion = datos.get("descripcion");
            modelo.addRow(new String[]{codigo, descripcion, marca, categoria});
        }
        this.jTable1.getColumnModel().getColumn(0).setPreferredWidth(80);
        this.jTable1.getColumnModel().getColumn(1).setPreferredWidth(368);
        this.jTable1.getColumnModel().getColumn(2).setPreferredWidth(130);
        this.jTable1.getColumnModel().getColumn(3).setPreferredWidth(130);
        this.jTable1.setRowSorter(new TableRowSorter<DefaultTableModel>(modelo));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane8 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton5 = new javax.swing.JButton();

        setMinimumSize(new java.awt.Dimension(975, 528));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Descripción", "Marca", "Categoria"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane8.setViewportView(jTable1);

        jButton5.setText("Imprimir");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 698, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton5)
                .addContainerGap(178, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton5)
                    .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 500, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(17, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        String f = "C:\\temp\\imprimir.pdf";
        try {
            Document document = new Document(PageSize.A4.rotate());
            PdfWriter.getInstance(document, new FileOutputStream(f));
            document.open();
            document.addTitle("Inventario");
            Paragraph preface = new Paragraph();
            Paragraph aux = new Paragraph("Rossi Sport", new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD));
            aux.setAlignment(Element.ALIGN_CENTER);
            preface.add(aux);
            preface.add(new Paragraph(" "));
            Date now = Calendar.getInstance().getTime();
            String s = new SimpleDateFormat("dd MMM yyyy hh:mm:ss").format(now);
            aux = new Paragraph("Fecha: " + s, new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD));
            aux.setAlignment(Element.ALIGN_RIGHT);
            preface.add(aux);
            preface.add(new Paragraph(" "));

            PdfPTable table = new PdfPTable(4);

            table.setWidths(new float[]{0.12f, 0.5f, 0.19f, 0.19f});

            PdfPCell c1;
            String[] headers = new String[]{"Código", "Descripción", "Marca", "Categoria"};
            for (String header : headers) {
                c1 = new PdfPCell(new Phrase(header));
                c1.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(c1);
            }
            table.setHeaderRows(1);

            TableModel t = this.jTable1.getModel();
            int j;
            for (int i = 0; i < t.getRowCount(); i++) {
                j = this.jTable1.convertRowIndexToModel(i);
                table.addCell((String) t.getValueAt(j, 0));
                table.addCell((String) t.getValueAt(j, 1));
                table.addCell((String) t.getValueAt(j, 2));
                table.addCell((String) t.getValueAt(j, 3));
            }

            preface.add(table);

            document.add(preface);
            document.close();
        } catch (Exception e) {
        }


        Desktop desktop = Desktop.getDesktop();

        if (desktop.isSupported(Desktop.Action.PRINT)) {
            try {
                File archivo_pdf = new File(f);
                desktop.print(archivo_pdf);
            } catch (Exception e1) {
                System.out.print("El sistema no permite imprimir usando la clase Desktop");
                e1.printStackTrace();
            }
        } else {
            System.out.print("El sistema no permite imprimir usando la clase Desktop");
        }
    }//GEN-LAST:event_jButton5ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton5;
    private javax.swing.JScrollPane jScrollPane8;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
